<?php
namespace Common\Model;
use Think\Model;

class UserCardModel extends Model{

	/**
	 *  检测用户是否已经绑定重复的汇通卡
	 *  @param int $userID 用户ID
	 *  @param str $pan 卡号
	 */
	public function isCard($userID,$pan){
		$where=array(
			"userID"=>$userID,
			"cardNum"=>$pan,
			"isOn"=>1
		);
		$result=$this->where($where)->find();
		return $result;
	}
	/*汇通卡新绑定方式*/
	public function addCardNew($userID,$pan,$password,$tokenID="0"){
		$data=array(
				"userID"=>$userID,
				"cardNum"=>$pan,
				"cardPassword"=>$password,
				"tokenID"=>$tokenID,
		        "tokenExpires"=>time()+60*60*24*7,
				"addTime"=>time(),
				"isOn"=>1,
				"oldornew"=>1,
				"is_default"=>1
		);
		$result=$this->data($data)->add();
		return $result;
	}
	public function updateCardNew($cardID,$userID,$pan,$password=null,$tokenID="0"){
		if($password){
			$data=array(
				"cardID"=>$cardID,
				"userID"=>$userID,
				"cardNum"=>$pan,
				"cardPassword"=>$password,
				"tokenID"=>$tokenID,
		        "tokenExpires"=>time()+60*60*24*7,
				"updateTime"=>time(),
				"isOn"=>1,
				"oldornew"=>1,
			);
		}else{
			$data=array(
				"cardID"=>$cardID,
				"userID"=>$userID,
				"cardNum"=>$pan,
				"tokenID"=>$tokenID,
		        "tokenExpires"=>time()+60*60*24*7,
				"updateTime"=>time(),
				"isOn"=>1,
				"oldornew"=>1,
				"is_default"=>1
			);
		}
		
		$result=$this->save($data);
		return $result;
	}
	/*解绑汇通卡*/
	public function unbindCard($userID,$pan){
		$where = array("userID"=>$userID,"cardNum"=>$pan);
		$data=$this->where($where)->find();
		$data['updateTime'] = time();
		$data['isOn'] = 0;
		$result=$this->save($data);
		return $result;
	}
	
	/**
	 *  绑定一张汇通卡
	 *  @param int $userID 用户ID
	 *  @param str $pan 卡号
	 *  @param str $tokenID 卡号token
	 */
	public function addCard($userID,$pan,$password,$tokenID="0"){
		$data=array(
				"userID"=>$userID,
				"cardNum"=>$pan,
				"cardPassword"=>$password,
				"tokenID"=>$tokenID,
		        "tokenExpires"=>time()+60*60*24*7,
				"addTime"=>time(),
				"isOn"=>1
		);
		$result=$this->data($data)->add();
		return $result;
	}
	
	/**
	 *  指定用户绑定的汇通卡
	 *  @param int $userID 用户ID
	 */
	public function userCardList($userID){
		$where=array(
			"userID"=>$userID,
			"isOn"=>1,
			"oldornew"=>0
		);
		$card=$this->where($where)->order("cardID desc")->select();
		return $card;
	}
        
        
	public function getUserCardList($userID){
		$where=array(
			"userID"=>$userID,
			"isOn"=>1
		);
		$card=$this->where($where)->order("cardID desc")->field("cardNum,addTime")->select();
		return $card;
	}
}
?>